#include "trn_line.h"

#include "graphics/graphics_util.h"
#include "num/rand.h"

TRNLine&	TRNLine::Instance()
{
	static TRNLine inst;
	return inst;
}


TRNLine::TRNLine()
{
	m_SprTronColor.Create("img/glow.png");
	m_SprTronColor.m_Color = ColorfRGBA(0.2f,0.5f,1.0f,0.1f);
	m_SprWithoutGlow.Create("img/without_glow.png");
	m_SprWithoutGlow.m_Color = ColorfRGBA(1.0f,1.0f,1.0f,1.0f);

	for(int i = 0; i < LINE_SPOT_BUFFER; i++)
	{
		m_Positions[i].x = -1;
		m_Positions[i].y = -1;

	}

	m_PosLast.x = -1.0f;
	m_PosLast.y = -1.0f;

}

void		TRNLine::MouseButtonDown( const math::Vec2& Pos)
{
	math::Vec2 PosTemp;
	math::Vec2 NewDir;
	const float THERE_HOLD = GraphicsUtil::InvH * 4.0f;

	

	if(m_PosLast.x != -1.0f && m_PosLast.y != -1.0f)
	{
		if( (Pos - m_PosLast).Magnitude() < THERE_HOLD)
			return;

		math::Vec2 Dir = Pos - m_PosLast;
		Dir.Normalize();
		NewDir  = Pos - m_PosLast; 

		PosTemp = m_PosLast;
		bool ToLoop = true;
		while( ToLoop   )
		{
			
			PosTemp +=  ( Dir * THERE_HOLD);
			NewDir = Pos - PosTemp;

			if( Dir.x > 0 && NewDir.x < 0)
				ToLoop = false;

			if( Dir.x < 0 && NewDir.x > 0)
				ToLoop = false;

			if( Dir.y > 0 && NewDir.y < 0)
				ToLoop = false;

			if( Dir.y < 0 && NewDir.y > 0)
				ToLoop = false;

			if(ToLoop)
				AddPoint(PosTemp);
		}

		AddPoint(Pos);
		

	}
	else
	{
		AddPoint(Pos);	
	}
	m_PosLast = Pos;
}

void		TRNLine::Render()
{
	math::Vec2 Pos;
	for(int i = 0; i < LINE_SPOT_BUFFER; i++)
	{
		Pos = m_Positions[LINE_SPOT_BUFFER - i - 1];
		if(Pos.x != -1.0f && Pos.y != -1.0f)
		{
			m_SprTronColor.m_Pos = Pos;

			m_SprTronColor.m_Color = ColorfRGBA(num::RAND32::Instance().RandFloat(0,0.01f),
												num::RAND32::Instance().RandFloat(0.7f,1.0f),
												num::RAND32::Instance().RandFloat(0.8f,1.0f),
												num::RAND32::Instance().RandFloat(0.05f,0.2f));
			m_SprTronColor.RenderRotated();

			
		}
	}

	for(int i = 0; i < LINE_SPOT_BUFFER; i++)
	{
		Pos = m_Positions[LINE_SPOT_BUFFER - i - 1];
		if(Pos.x != -1.0f && Pos.y != -1.0f)
		{
			

			m_SprWithoutGlow.m_Pos = Pos;			
			m_SprWithoutGlow.RenderRotated();
			
		}
	}
}

void		TRNLine::AddPoint(const math::Vec2& Pos)
{
	for(int i = 0; i < LINE_SPOT_BUFFER - 1; i++)
	{
		m_Positions[LINE_SPOT_BUFFER - i - 1] = m_Positions[LINE_SPOT_BUFFER - i - 2];
	}
	m_Positions[0] = Pos;
	
}